<?php

namespace App\Services\Message;

use App\Libs\Commons\MyLogger;
use App\Libs\Commons\MyMessage;
use App\Services\Wechat\MiniProgramService;
use App\Services\Wechat\WorkService;
use EasyWeChat\Kernel\Messages\TextCard;

/**
 * 消息推送服务
 *
 * @example
 * @author mengsen
 * @since
 */
class PushService
{
    // 短信推送
    public static function sms($param = [])
    {
        return YunpianService::send($param);
    }

    // 小程序推送
    public static function miniprogram($param = [])
    {
        try {
            $app = MiniProgramService::getInstance();
            $result = $app->subscribe_message->send($param);
            MyLogger::info('小程序推送响应', $result);
            if ($result['errcode'] != 0) {
                throw new \Exception($result['errmsg'], $result['errcode']);
            }
            return $result;
        } catch (\Throwable $e) {
            MyLogger::error('小程序推送响应', ['code' => $e->getCode(), 'msg' => $e->getMessage()]);
            throw new \Exception($e->getMessage(), $e->getCode());
        }
    }

    // 企业微信推送
    public static function work($param = [])
    {

        try {
            $touser = $param['touser'];
            unset($param['touser']);
            if (empty($touser)) {
                throw new \Exception("消息接收者不可为空", MyMessage::PARAM_EMPTY);
            }

            $message = [];
            switch ($param['type'] ?? 0) {
                case 'textcard':
                    $message = new TextCard($param);
                    break;
                default:
                    $message = new TextCard($param);
                    break;
            }

            $app = WorkService::getInstance();
            $result = $app->messenger->message($message)->toUser($touser)->send();
            MyLogger::info('企业微信推送响应', $result);
            return $result;
        } catch (\Throwable $e) {
            MyLogger::error('企业微信推送响应', ['code' => $e->getCode(), 'msg' => $e->getMessage()]);
            throw new \Exception($e->getMessage(), 0);
        }
    }
}
